package org.ngmj.server.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.ngmj.config.ServicesFactory;
import org.ngmj.message.RpcRequestMessage;
import org.ngmj.message.RpcResponseMessage;
import org.ngmj.server.exception.NoStackTraceException;

import java.lang.reflect.Method;

@Slf4j
@ChannelHandler.Sharable
public class RpcRequestMessageHandler extends SimpleChannelInboundHandler<RpcRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequestMessage rpcRequestMessage) {
        RpcResponseMessage response = new RpcResponseMessage();
        response.setSequenceId(rpcRequestMessage.getSequenceId());
        try {
            Class<?> aClass = Class.forName(rpcRequestMessage.getInterfaceName());
            Object service = ServicesFactory.getService(aClass);
            Method method = service.getClass().getMethod(rpcRequestMessage.getMethodName(), rpcRequestMessage.getParameterTypes());
            Object invoke = method.invoke(service, rpcRequestMessage.getParameterValue());
            response.setReturnValue(invoke);
        } catch (Exception e) {
            log.error("Exception:", e);
            response.setExceptionValue(new NoStackTraceException("远程调用出错: " + e.getCause().getMessage()));
        } finally {
            ctx.channel().writeAndFlush(response);
            log.info("msg:{}", response);
        }
    }
}
